package com.yuan.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuan.bean.Book;
import com.yuan.bean.UserLogin;
import com.yuan.service.BookInformService;
import com.yuan.service.LibraryCardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class BookTableController {

    @Autowired
    BookInformService bookInformService;

    @Autowired
    LibraryCardService libraryCardService;

    //动态条件查询
    @RequestMapping("/library")
    public String selectAllByCondition(@RequestParam(defaultValue = "1", value = "pageNum") Integer pageNum, Model model,
                                       @RequestParam(value = "bookName", defaultValue = "") String bookName,
                                       @RequestParam(defaultValue = "", value = "author") String author,
                                       @RequestParam(value = "category", defaultValue = "") String category) {
        //前端回显数据
        model.addAttribute("category", category);
        model.addAttribute("bookName", bookName);
        model.addAttribute("author", author);

        PageHelper.startPage(pageNum, 5);
        category = "%" + category + "%";
        bookName = "%" + bookName + "%";
        author = "%" + author + "%";
        List<Book> books = bookInformService.selectAllByCondition(category, bookName, author);

        PageInfo<Book> pageInfo = new PageInfo<>(books);
        model.addAttribute("pageInfo", pageInfo);
        return "library";
    }

    //处理借书请求
    @RequestMapping("/borrow")
    public String borrow(@RequestParam("bookId") Integer bookId, Model model, HttpSession session) {
        final UserLogin user = (UserLogin) session.getAttribute("User");
        Integer userId = user.getUserId();
        final boolean b = libraryCardService.borrowBook(userId, bookId);
        model.addAttribute("msg", b);
        return "library";
    }


}
